<?php
require_once(dirname(__FILE__).'/Abstract.php');
class Message extends AbstractPatientController {
/**
 * Message
 * 
 * Allows user to manage his messages like writing, reading, replying or deleting
 * 
 * @package Seowebd : Medic - Online
 * @author Seowebd
 * @copyright 2014
 * @version $Id$
 * @access public
 */

	public function indexAction() 
    {
        $this->session->set_userdata(array( 'filter_by' => 'sender', 'filter_val' => 'doctor'));
        $this->inboxAction();
    }
    
    public function inboxAction()
    {
    	//$d = array();
        $joinFeature = array();
        
        $joinFeature[] = array(
            'type'     => 'LEFT JOIN', // LEFT JOIN, RIGHT JOIN, INNER JOIN, etc...
            'table'    => '`medic_consultation` cons', // An existing table with alias 
            'onclause' => 'cons.id_consultation = ConsultationMessageORM.id_consultation', // 
            'select'   => 'cons.id_consultation', // For select clause
        );
        $joinFeature[] = array(
            'type'     => 'LEFT JOIN', // LEFT JOIN, RIGHT JOIN, INNER JOIN, etc...
            'table'    => '`medic_user_doctor` doctor', // An existing table with alias 
            'onclause' => 'doctor.id_doctor = cons.id_doctor', // 
            'select'   => 'doctor.`medical_id` AS doctor_medical_id, doctor.`phone` AS doctor_phone, doctor.`profession` AS doctor_profession, 
                            doctor.`address` AS doctor_address, doctor.`description` AS doctor_description', // For select clause
        );
        $joinFeature[] = array(
            'type'     => 'LEFT JOIN', // LEFT JOIN, RIGHT JOIN, INNER JOIN, etc...
            'table'    => '`medic_user_entity` doctor_entity', // An existing table with alias 
            'onclause' => 'doctor.id_doctor = doctor_entity.id_user', // 
            'select'   => 'CONCAT(LEFT(doctor_entity.`firstname`, 1), \'. \', doctor_entity.`lastname`) AS doctor_name, doctor_entity.`email` AS doctor_email', // For select clause
        );
        $joinFeature[] = array(
            'type'     => 'LEFT JOIN', // LEFT JOIN, RIGHT JOIN, INNER JOIN, etc...
            'table'    => '`medic_user_patient` patient', // An existing table with alias 
            'onclause' => 'patient.id_patient = cons.id_patient', // 
            'select'   => 'patient.`birthday` AS patient_birthday, patient.`phone` AS patient_phone, patient.`profession` AS patient_profession, patient_entity.`id_user` AS patient_id, 
                            patient.`pobox` AS patient_pobox, patient.`town` AS patient_town, patient.`nb_secur_social` AS patient_nb_secur_social, 
                            patient.`cmu` AS patient_cmu, patient.`address` AS patient_address', // For select clause
        );
        $joinFeature[] = array(
            'type'     => 'LEFT JOIN', // LEFT JOIN, RIGHT JOIN, INNER JOIN, etc...
            'table'    => '`medic_user_entity` patient_entity', // An existing table with alias 
            'onclause' => 'patient.id_patient = patient_entity.id_user', // 
            'select'   => 'CONCAT(LEFT(patient_entity.`firstname`, 1), \'. \', patient_entity.`lastname`) AS patient_name, patient_entity.`email` AS patient_email', // For select clause
        );
        $joinFeature[] = array(
            'type'     => 'LEFT JOIN', // LEFT JOIN, RIGHT JOIN, INNER JOIN, etc...
            'table'    => '`medic_user_entity` users', // An existing table with alias 
            'onclause' => 'users.id_user = cons.id_patient', // 
            'select'   => 'users.lastname, users.firstname', // For select clause
        );
        $joinFeature[] = array(
            'type'     => 'LEFT JOIN',
            'table'    => '`medic_user_role_lang` url',
            'onclause' => 'users.id_role = url.id_role AND url.lang = \''. $this->session->userdata('lang') .'\'',
            'select'   => 'url.`name` AS role_name',
        );
        
        $d = $this->initListing('ORM/Consultation/ConsultationMessageORM', 'id_message', 'medic_consultation_message', false, null, null, $joinFeature);
        
        $d['title'] = $this->l('My incomming messages');
        $this->load->model('Metier/Consultation/ConsultationMetier');
        
        //$d['messages'] = $this->ConsultationMetier->getMessagesToPatient($this->session->userdata('id_user'), array());

        $d['title_for_layout'] = $this->l('Inbox messages.');
        $d['menu'] = 'messages';
        $d['page_name'] = 'messages_list';
        
        $this->load->view('Templates/Layouts/Patient/header', $d);
        $this->load->view('Patient/Message/Inbox', $d);
        $this->load->view('Templates/Layouts/Patient/footer', $d);
    }
    
    public function writeAction(){
        
        $d['title'] = $this->l('Write');
        $this->load->model('Metier/Consultation/ConsultationMetier');
        if ($this->input->post('btn_submit') !== false){
             // Initialized the form validation
            $config = array(
               array(
                     'field'   => 'message', 
                     'label'   => $this->l('First name'), 
                     'rules'   => 'trim|required|xss_clean'
                  ),
               array(
                     'field'   => 'context', 
                     'label'   => $this->l('Context'), 
                     'rules'   => 'trim|required|xss_clean'
                  ),
               array(
                     'field'   => 'id_consultation', 
                     'label'   => $this->l('Consultation'), 
                     'rules'   => 'trim|required|xss_clean'
                  ),
            );
            $this->form_validation->set_rules($config);
            if ($this->form_validation->run() == FALSE ){
                $this->session->set_flashdata('errorMessage', $this->l('An error occured. Please check filled data and try again.'));
            } else {
                $this->load->model('ORM/Consultation/ConsultationMessageORM');
                // Initialize the new record
                $record = array(
                    'message'        => $this->input->post('message'),
                    'context'        => $this->input->post('context'),
                    'id_consultation'=> $this->input->post('id_consultation'),                   
                    // Automatic fill
                    'sender'         => 'patient',                             
                    'readed'         => '0',                           
                    'deleted'        => '00',
                    'date_add'       => @date('Y-m-d H:i:s'),
                );
                // Create the new message
                if ($this->ConsultationMessageORM->save($record)) {
                    // Redirect to the sign in form
                    redirect('Patient/Message/inbox');
                    die();
                } else {
                    $this->session->set_flashdata('errorMessage', $this->l('An error occured while saving your message. Please try again.'));
                }
            }
        }
        //$d['message'] = $this->ConsultationMetier->getMessageByIdFromDoctor($id_message, array());
        
        $d['title_for_layout'] = $this->l('Write a message.');
        $d['menu'] = 'messages';
        $d['page_name'] = 'write_message';
        
        $this->load->view('Templates/Layouts/Patient/header', $d);
        $this->load->view('Patient/Message/Write', $d);
        $this->load->view('Templates/Layouts/Patient/footer', $d);
    }
    
    public function readAction($id_message = NULL)
    {
        $d = array();
        $d['title'] = $this->l('Message ');
        $this->load->model('Metier/Consultation/ConsultationMetier');
        $this->load->model('ORM/Consultation/ConsultationMessageORM');
        $objMsg = $this->ConsultationMessageORM->getByIdMessageAndSender($id_message, 'doctor');
        if ($objMsg):
            $ok = TRUE;
        endif;
        if ($ok):
            $this->ConsultationMessageORM->save(array('id_message'=>$objMsg->id_message, 'readed'=>'1'));
        endif;
        $d['message'] = $this->ConsultationMetier->getMessageByIdFromDoctor($id_message, array());
        
        $d['title_for_layout'] = $this->l('Read message.');
        $d['menu'] = 'messages';
        $d['page_name'] = 'read_message';
        
        $this->load->view('Templates/Layouts/Patient/header', $d);
        $this->load->view('Patient/Message/Read', $d);
        $this->load->view('Templates/Layouts/Patient/footer', $d);
    }

    public function replyAction($id_message = NULL)
    {
        $d = array();
        $d['title'] = $this->l('Reply to');
        $this->load->model('Metier/Consultation/ConsultationMetier');
        if ($this->input->post('btn_submit') !== false){
             // Initialized the form validation
            $config = array(
               array(
                     'field'   => 'message', 
                     'label'   => $this->l('First name'), 
                     'rules'   => 'trim|required|xss_clean'
                  ),
               array(
                     'field'   => 'context', 
                     'label'   => $this->l('Context'), 
                     'rules'   => 'trim|required|xss_clean'
                  ),
               array(
                     'field'   => 'id_consultation', 
                     'label'   => $this->l('Consultation'), 
                     'rules'   => 'trim|required|xss_clean'
                  ),
            );
            $this->form_validation->set_rules($config);
            if ($this->form_validation->run() == FALSE ){
                $this->session->set_flashdata('errorMessage', $this->l('An error occured. Please check filled data and try again.'));
            } else {
                $this->load->model('ORM/Consultation/ConsultationMessageORM');
                // Initialize the new record
                $record = array(
                    'message'        => $this->input->post('message'),
                    'context'        => $this->input->post('context'),
                    'id_consultation'=> $this->input->post('id_consultation'),                   
                    // Automatic fill
                    'sender'         => 'patient',                             
                    'readed'         => '0',                           
                    'deleted'        => '00',
                    'date_add'       => @date('Y-m-d H:i:s'),
                );
                // Create the new message
                if ($this->ConsultationMessageORM->save($record)) {
                    // Redirect to the sign in form
                    redirect('Patient/Message/inbox');
                    die();
                } else {
                    $this->session->set_flashdata('errorMessage', $this->l('An error occured while saving your message. Please try again.'));
                }
            }
        }
        $d['message'] = $this->ConsultationMetier->getMessageByIdFromDoctor($id_message, array());
        
        $d['title_for_layout'] = $this->l('Reply to a message.');
        $d['menu'] = 'messages';
        $d['page_name'] = 'reply_message';
        
        $this->load->view('Templates/Layouts/Patient/header', $d);
        $this->load->view('Patient/Message/Reply', $d);
        $this->load->view('Templates/Layouts/Patient/footer', $d);
    }
}

